var ctx = window.daijia.ctx;

var driverArr=[];//服务人员标记集合
var driverPositionArr=[];//服务人员位置集合


var count=0;
function initialise(){
	
	if($(".innerDrivers").length>count){
		var driverlng=$($(".innerDrivers")[count]).find("input[name=driverlng]").val();
		var driverlat=$($(".innerDrivers")[count]).find("input[name=driverlat]").val();
		var toplacelng=$($(".innerDrivers")[count]).find("input[name=toplacelng]").val();
		var toplacelat=$($(".innerDrivers")[count]).find("input[name=toplacelat]").val();
		
		$.ajax({
            url: ctx+'/driver/listmodeInitialise',
            type: "GET",
            data: {'driverlng':driverlng,'driverlat':driverlat,'toplacelng':toplacelng,'toplacelat':toplacelat},
            dataType: 'json',
            async:false,
            success:function(data){
            	if(data.position){
    				$($(".innerDrivers")[count]).find(".driver_position").html(data.position);
    		  	}
    			else{
    				$($(".innerDrivers")[count]).find(".driver_position").html("定位失败");
    			}
    			
    			if(data.timestr){
    				$($(".innerDrivers")[count]).find(".toplace_time").html('('+data.timestr+')');
    		  	}
    			else{
    				$($(".innerDrivers")[count]).find(".toplace_time").html("未知时间");
    			}
            }
        });
		
		count++;
		setTimeout("initialise()",1500);
	}
	else{
		count=0;
		startUpdateDriverPosition();
	}
}

function startUpdateDriverPosition(){
	if(null!=driverPositionArr && driverPositionArr.length>0){
		var lng=driverPositionArr[0].lng;
		var lat=driverPositionArr[0].lat;
		$.ajax({
	        url: ctx+'/driver/listmodeInitialise',
	        type: "GET",
	        data: {'driverlng':lng,'driverlat':lat},
	        dataType: 'json',
	        async:false,
	        success:function(data){
	        	if(data.position){
					$("#driver_panel_"+driverPositionArr[0].id+"").find(".driver_position").html(data.position);
			  	}
	        }
	    });
		removeDriverPositionArr(driverPositionArr[0].id);
	}
	setTimeout("startUpdateDriverPosition()",1500);
}

function getDriverPosition(driverId){
	if(driverPositionArr==null || driverPositionArr.length==0){
		return null;
	}
	var position=null;
	$(driverPositionArr).each(function(index,element){
		if(element.id == driverId){
			position=element;
			return;
		}
	});
	return position;
}

function removeDriverPositionArr(driverId){
	if(null!=driverPositionArr && driverPositionArr.length>0){
		$(driverPositionArr).each(function(index,element){
			if(element.id == driverId){
				driverPositionArr.splice(index,1);
				return;
			}
		});
	}
}

var initWebSocket = function() {
	//建立长连接
	var sock = new SockJS('http://' + window.location.host + '/push', null, {
		  debug:true,
         'protocols_whitelist': ['websocket', 'xhr-streaming','iframe-eventsource', 'iframe-htmlfile','xhr-polling', 'jsonp-polling'] });
	
	sock.onopen = function() {
		sock.send("{'command':'connected'}");
	};
	sock.onmessage = function(evt) {
		var result = $.parseJSON(evt.data);
		
		if(result.type == "driverOnline"){//服务人员上线
			var driver=result.data;
			
			var workingOrders=driver.workingOrders;
			var yupaidanOrders=driver.yupaidanOrders;
			
			//进行中订单
			var content1="";
			if(workingOrders && workingOrders.size>0){
				$(workingOrders).each(function(index,element){
					var fromPlace=element.fromPlace;
		    		var subFromPlace="";
		    		if(fromPlace.length>5){
		    			subFromPlace=fromPlace.substring(0,5);
		    		}
		    		else{
		    			subFromPlace=fromPlace;
		    		}
		    		
		    		var innerContent="";
		    		if(element.hasToPlace){
		    			var toPlace=element.toPlace;
			    		var subToPlace="";
			    		if(toPlace.length>5){
			    			subToPlace=toPlace.substring(0,5);
			    		}
			    		else{
			    			subToPlace=toPlace;
			    		}
		    			innerContent+='<input type="hidden" name="toplacelng" value="'+element.toPlaceLongitude+'">'+
						    			'<input type="hidden" name="toplacelat" value="'+element.toPlaceLatitude+'">'+
							    		'<a title="'+element.toPlace+'">'+subToPlace+'</a>'+
							    		'<br/>'+
							    		'<span class="timeColor toplace_time">计算中...</span>';
		    		}
		    		else{
		    			innerContent+='<span class="timeColor">未知目的地<br/>未知时间</span>';
		    		}
		    		
		    		content1+='<p style="text-align:center;">'+
								    '<span style="float:left;">'+
									    '<a title="'+fromPlace+'">'+subFromPlace+'</a>'+
									    '<br/>'+
									    '<span class="timeColor">('+element.serverTimeHI+')</span>'+
								    '</span>'+
								    '→'+
								    '<span class="right-span" style="float:right;">'+
								    	innerContent+
								    '</span>'+
								'</p>'+
							    '<hr/>';
				});
			}
			
			//预派单订单
			var content2="";
			if(yupaidanOrders && yupaidanOrders.size>0){
				$(yupaidanOrders).each(function(index,element){
					var fromPlace=element.fromPlace;
		    		var subFromPlace="";
		    		if(fromPlace.length>8){
		    			subFromPlace=fromPlace.substring(0,8);
		    		}
		    		else{
		    			subFromPlace=fromPlace;
		    		}
					content2+='<div id="newOrders_div_'+element.id+'">'+
								    '<p class="newOrders_p" style="text-align:right;padding-right:13px;">'+
								    '<span style="float:left;"><a title="'+fromPlace+'">'+subFromPlace+'</a></span>'+
								    '('+element.serverTimeHI+')'+
								    '<span class="revoke_yupaidan" style="float:right;"><a data-value="'+element.id+'" href="javascript:;"><img src="'+ctx+'/assets/css/images/delete.png" /></a></span>'+
							    '</p>'+
							    '<hr/>'+
					    	'</div>';
				});
			}
			
			
			$("#driver_panels").prepend('<div id="driver_panel_'+driver.id+'" class="panel panel-default innerDrivers" style="display:none;">'+
					  '<div class="panel-heading">'+
					  	'<div class="panel-heading-inner">'+driver.realname+' <span class="driver_position">定位中...</span></div>'+
					  '</div>'+
					  '<div class="panel-body scrollDrivers">'+
					  
					    '<input type="hidden" name="driverlng" value="'+driver.longitude+'">'+
					    '<input type="hidden" name="driverlat" value="'+driver.latitude+'">'+
					    '<div id="driverWorkingOrder_'+driver.id+'">'+
					    	content1+
					    '</div>'+
					    
					    '<div id="driverYupaidanOrder_'+driver.id+'">'+
					    	content2+
						'</div>'+
						
					  '</div>'+
					'</div>');
			
			$("#driver_panel_"+driver.id+"").show(2000);
			$.scojs_message(driver.realname+"已经上线", $.scojs_message.TYPE_OK);
			
			$("#driverWorkingOrder_"+driver.id+"").find("p").each(function(index,element){
				var this_p=$(this);
				if($(this).find(".toplace_time").length>0){
					var driverlng=driver.longitude;
					var driverlat=driver.latitude;
					var toplacelng=this_p.find("input[name=toplacelng]").val();
					var toplacelat=this_p.find("input[name=toplacelat]").val();
					$.ajax({
			            url: ctx+'/driver/listmodeInitialise',
			            type: "GET",
			            data: {'driverlng':driverlng,'driverlat':driverlat,'toplacelng':toplacelng,'toplacelat':toplacelat},
			            dataType: 'json',
			            async:false,
			            success:function(data){
			            	if(data.position){
			            		$("#driver_panel_"+driver.id+"").find(".driver_position").html(data.position);
			    		  	}
			    			else{
			    				$("#driver_panel_"+driver.id+"").find(".driver_position").html("定位失败");
			    			}
			    			
			    			if(data.timestr){
			    				this_p.find(".toplace_time").html('('+data.timestr+')');
			    		  	}
			    			else{
			    				this_p.find(".toplace_time").html("未知时间");
			    			}
			            }
			        });
				}
			});
			
		}
		else if(result.type == "driverOffline"){//服务人员下线
			var driverId=result.data.id;
			$("#driver_panel_"+driverId+"").hide(1000);
    		setTimeout(function(){
    			$("#driver_panel_"+driverId+"").remove();
    		}, 1000);
		}
		else if(result.type == "newOrders"){//添加新订单
			$(result.data.firsetObject).each(function(index,order){
				$("#newOrder_ul").append(
		    			'<li id="newOrder_'+order.id+'" class="list-group-item">'+
						    '<input type="radio" name="newOrderRadios" value="'+order.id+'">'+
						    ' '+order.serverTimeHI+' '+order.fromPlace+
					   	'</li>');
		    	$("#newOrder_"+order.id+"").show(1000);
			});
			document.getElementById('new_order_play').play();//播放声音
		}
		else if(result.type == "paidan"){//派单
			var driverId=result.data.firsetObject;
	    	var order=result.data.secondObject;
	    	
	    	$.scojs_message('订单'+order.orderNumber+"派单成功", $.scojs_message.TYPE_OK);
	    	
	    	if($("#newOrder_"+order.id+"").length>0){
	    		$("#newOrder_"+order.id+"").hide(1000);
	    		setTimeout(function(){
	    			$("#newOrder_"+order.id+"").remove();
	    		}, 1000);
	    	}
	    	$("#drivers_ul").html("");

    		var fromPlace=order.fromPlace;
    		var subFromPlace="";
    		if(fromPlace.length>5){
    			subFromPlace=fromPlace.substring(0,5);
    		}
    		else{
    			subFromPlace=fromPlace;
    		}
    		$("#driverWorkingOrder_"+driverId+"").append(
    			'<p style="text-align:center;">'+
				    '<span style="float:left;">'+
					    '<a title="'+fromPlace+'">'+subFromPlace+'</a>'+
					    '<br/>'+
					    '('+order.serverTimeHI+')'+
				    '</span>'+
				    '→'+
				    '<span class="right-span" style="float:right;">'+
				    		'未知目的地<br/>未知时间'+
				    '</span>'+
    			'</p>'+
    			'<hr/>');

	    	
	    	$("#newOrders_div_"+order.id+"").remove();
	    	
	    }
		else if(result.type == "fillorderv2"){
			var driverId=result.data.firsetObject;
			var order=result.data.secondObject;
			
			var fromPlace=order.fromPlace;
    		var subFromPlace="";
    		if(fromPlace.length>5){
    			subFromPlace=fromPlace.substring(0,5);
    		}
    		else{
    			subFromPlace=fromPlace;
    		}
    		$("#driverWorkingOrder_"+driverId+"").append(
    			'<p style="text-align:center;">'+
				    '<span style="float:left;">'+
					    '<a title="'+fromPlace+'">'+subFromPlace+'</a>'+
					    '<br/>'+
					    '('+order.serverTimeHI+')'+
				    '</span>'+
				    '→'+
				    '<span class="right-span" style="float:right;">'+
				    		'未知目的地<br/>未知时间'+
				    '</span>'+
    			'</p>'+
    			'<hr/>');
		}
		else if(result.type == "getrushorder"){//服务人员抢单 直接接受
	    	var driverId=result.data.firsetObject;
	    	var order=result.data.secondObject;
	    	
	    	var fromPlace=order.fromPlace;
    		var subFromPlace="";
    		if(fromPlace.length>5){
    			subFromPlace=fromPlace.substring(0,5);
    		}
    		else{
    			subFromPlace=fromPlace;
    		}
    		$("#driverWorkingOrder_"+driverId+"").append(
    			'<p style="text-align:center;">'+
				    '<span style="float:left;">'+
					    '<a title="'+fromPlace+'">'+subFromPlace+'</a>'+
					    '<br/>'+
					    '('+order.serverTimeHI+')'+
				    '</span>'+
				    '→'+
				    '<span class="right-span" style="float:right;">'+
				    		'未知目的地<br/>未知时间'+
				    '</span>'+
    			'</p>'+
    			'<hr/>');
	    	
	    }
		else if(result.type == "yupaidan"){//预派单
			$.scojs_message('派单成功', $.scojs_message.TYPE_OK);
			
			var driverId=result.data.firsetObject;
	    	var order=result.data.secondObject;
	    	
	    	if($("#newOrder_"+order.id+"").length>0){
	    		$("#newOrder_"+order.id+"").hide(1000);
	    		setTimeout(function(){
	    			$("#newOrder_"+order.id+"").remove();//移除订单
	    		}, 1000);
	    	}
	    	$("#drivers_ul").html("");
	    	
    		var fromPlace=order.fromPlace;
    		var subFromPlace="";
    		if(fromPlace.length>8){
    			subFromPlace=fromPlace.substring(0,8);
    		}
    		else{
    			subFromPlace=fromPlace;
    		}
    		$("#driverYupaidanOrder_"+driverId+"").append(
    			'<div id="newOrders_div_'+order.id+'">'+
    			'<p class="newOrders_p" style="text-align:center;">'+
				    '<span style="float:left;"><a title="'+fromPlace+'">'+subFromPlace+'</a></span>'+
				    '('+order.serverTimeHI+')'+
				    '<span class="revoke_yupaidan" style="float:right;"><a data-value="'+order.id+'" href="javascript:;"><img src="'+ctx+'/assets/css/images/delete.png" /></a></span>'+
			    '</p>'+
			    '<hr/>'+
			    '</div>');
	    		
		}
		else if(result.type == "revoke"){//收回
			var order=result.data.firsetObject;
	    	var driverId=result.data.secondObject;
	    	
	    	$("#newOrder_ul").append(
	    			'<li id="newOrder_'+order.id+'" class="list-group-item">'+
					    '<input type="radio" name="newOrderRadios" value="'+order.id+'">'+
					    ' '+order.serverTimeHI+' '+order.fromPlace+
				   	'</li>');
	    	$("#newOrder_"+order.id+"").show(1000);
	    	
	    	$("#driverWorkingOrder_"+driverId+"").html("");
	    	
		}
		else if(result.type == "powerrevoke"){//强制收回
			var order=result.data.firsetObject;
	    	var driverId=result.data.secondObject;
			$("#driverWorkingOrder_"+driverId+"").html("");
			$("#newOrder_ul").append(
	    			'<li id="newOrder_'+order.id+'" class="list-group-item">'+
					    '<input type="radio" name="newOrderRadios" value="'+order.id+'">'+
					    ' '+order.serverTimeHI+' '+order.fromPlace+
				   	'</li>');
	    	$("#newOrder_"+order.id+"").show(1000);
		}
		else if(result.type == "revokeyupaidan"){//收回预派单
			var order=result.data.firsetObject;
	    	var driverId=result.data.secondObject;
	    	
	    	$.scojs_message('收回成功', $.scojs_message.TYPE_OK);
	    	
	    	$("#newOrder_ul").append(
	    			'<li id="newOrder_'+order.id+'" class="list-group-item">'+
					    '<input type="radio" name="newOrderRadios" value="'+order.id+'">'+
					    ' '+order.serverTimeHI+' '+order.fromPlace+
				   	'</li>');
	    	$("#newOrder_"+order.id+"").show(1000);
	    	
	    	$("#newOrders_div_"+order.id+"").remove();
		}
		else if(result.type == "cancel"){//销单
			var orderId=result.data.firsetObject;
	    	var driverId=result.data.secondObject;
	    	var oldStatus=result.data.thirdObject;
	    	if(oldStatus==0){
	    		if($("#newOrder_"+orderId+"").length>0){
		    		$("#newOrder_"+orderId+"").hide(1000);
		    		setTimeout(function(){
		    			$("#newOrder_"+orderId+"").remove();//移除订单
		    		}, 1000);
		    	}
	    	}
	    	else{
	    		if($("#newOrder_"+orderId+"").length>0){
		    		$("#newOrder_"+orderId+"").hide(1000);
		    		setTimeout(function(){
		    			$("#newOrder_"+orderId+"").remove();//移除订单
		    		}, 1000);
		    	}
	    		$("#driverWorkingOrder_"+driverId+"").html("");
	    	}
	    	
		}
		else if(result.type == "powercancel"){//强制销单
			var driverId=result.data.secondObject;
			$("#driverWorkingOrder_"+driverId+"").html("");
		}
		else if(result.type == "cancelyupaidan"){//销单预派单
			var order=result.data.firsetObject;
			$("#newOrders_div_"+order.id+"").remove();
		}
		else if(result.type == "qingqiujie"){
			var order=result.data.firsetObject;
			if(order.hasToPlace){
				if($("#driverWorkingOrder_"+order.driverId+"").length>0){
					var toPlace=order.toPlace;
		    		var subToPlace="";
		    		if(toPlace.length>5){
		    			subToPlace=toPlace.substring(0,5);
		    		}
		    		else{
		    			subToPlace=toPlace;
		    		}
					$("#driverWorkingOrder_"+order.driverId+"").find(".right-span").html(
							'<input type="hidden" name="toplacelng" value="'+order.toPlaceLongitude+'">'+
			    			'<input type="hidden" name="toplacelat" value="'+order.toPlaceLatitude+'">'+
			    			'<a title="'+toPlace+'">'+subToPlace+'</a>'+
				    		'<br/>'+
				    		'<span class="toplace_time">计算中...</span>');
					
					var driverlng=$("#driverWorkingOrder_"+order.driverId+"").parent().parent().find("input[name=driverlng]").val();
					var driverlat=$("#driverWorkingOrder_"+order.driverId+"").parent().parent().find("input[name=driverlat]").val();
					var toplacelng=order.toPlaceLongitude;
					var toplacelat=order.toPlaceLatitude;
					
					$.ajax({
			            url: ctx+'/driver/listmodeInitialise',
			            type: "GET",
			            data: {'driverlng':driverlng,'driverlat':driverlat,'toplacelng':toplacelng,'toplacelat':toplacelat},
			            dataType: 'json',
			            async:false,
			            success:function(data){
			    			if(data.timestr){
			    				$("#driverWorkingOrder_"+order.driverId+"").find(".toplace_time").html('('+data.timestr+')');
			    		  	}
			    			else{
			    				$("#driverWorkingOrder_"+order.driverId+"").find(".toplace_time").html("未知时间");
			    			}
			            }
			        });
					
				}
			}
		}
		else if(result.type == "finish"){//完成
			$.scojs_message(result.data.message, $.scojs_message.TYPE_OK);
			var driverId=result.data.firsetObject;
			$("#driverWorkingOrder_"+driverId+"").html("");
		}
		else if(result.type == "updateUserLocation"){//更新服务人员坐标
	    	var data = result.data;
	    	var driverId=data.firsetObject;
    		var location = data.secondObject;
    		var longitude=location.longitude;
    		var latitude=location.latitude;
	    	
    		var position=getDriverPosition(driverId);
    		if(null==position){
    			driverPositionArr.push({'id':driverId,'lng':longitude,'lat':latitude});
    		}
    		else{
    			removeDriverPositionArr(driverId);
    			driverPositionArr.push({'id':driverId,'lng':longitude,'lat':latitude});
    		}
	    }
		
	};
	sock.onclose = function() {
		sock.close(); //关闭TCP连接
		setTimeout(function(){
			initWebSocket();
		}, 3000);
    };
    
};

$(document).ready(function(){

	initialise();
	
	initWebSocket();
	
    //点击新单
    $(document).on("click","input[name=newOrderRadios]",function(){
    	$("input[name=newOrderRadios]").attr("disabled",true);
    	$.get(ctx+'/driver/tuijianDrivers',{'orderid':$(this).val()},function(result){
    		$("#drivers_ul").html("");
    		driverArr=[];
    		if(result && result.length>0){
    			$(result).each(function(index,element){
    				$("#drivers_ul").append('<li class="list-group-item tuijian-siji-li" data-driver-id="'+element.id+'">'+element.realname+'   '+element.phone+'   '+parseInt(element.distance)+'公里<button class="btn btn-default btn-xs paidan" data-driver-id="'+element.id+'">派单</button></li>');
    				driverArr.push({'id':element.id,'name':element.realname+'   '+element.phone,'pinyin':element.namePinyin});
    			});
    		}
    		$("input[name=newOrderRadios]").attr("disabled",false);
    	});
    });
    
    $(document).on("click",".tuijian-siji-li",function(){
    	$("#drivers_ul .list-group-item-info").removeClass("list-group-item-info");
    	$(this).addClass("list-group-item-info");
    	
    	$(".panel-info").addClass("panel-default").removeClass("panel-info");
    	$("#driver_panel_"+$(this).attr("data-driver-id")+"").removeClass("panel-default").addClass("panel-info");
    });
    
    $('#search_driver').AutoComplete({
    	'listStyle': 'custom',
    	'data': function(){
            return driverArr;
        },
        'matchHandler': function(keyword, data){
        	if(null!=data.pinyin){
        		return data.name.indexOf(keyword) >= 0 || data.pinyin.indexOf(keyword)>= 0;
        	}
        	else{
        		return data.name.indexOf(keyword) >= 0;
        	}
        },
        'createItemHandler': function(index, data){
        	var regex = RegExp("("+$("#search_driver").val().replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1")+")", 'ig');
            var name = data.name.replace(regex, "<span style='color:red;'>$1</span>");
            return "<a>"+name+"</a>";
        },
        'afterSelectedHandler': function(data){
        	$("#drivers_ul li[data-driver-id="+data.id+"]").click();
        	$("#drivers_ul li").each(function(i,e){
        		if($(e).attr("data-driver-id")!=data.id){
        			$(e).remove();
        		}
        	});
        	driverArr=[];
        }
    });
    
    $(document).on("mouseover",".newOrders_p",function(){
    	$(this).find(".revoke_yupaidan").show();
    }).on("mouseleave",".newOrders_p",function(){
    	$(this).find(".revoke_yupaidan").hide();
    });
    
    
    //派单
    $(document).on("click",".paidan",function(){
    	if($("input[name=newOrderRadios]:checked").length==0){
    		alert("请先选择订单");
    		return false;
    	}
    	
    	var thisbutton=$(this);
    		
    	if(window.confirm('确认要派单给该服务人员吗？')){
    		$(".paidan").attr("disabled",true);
    		$.post(ctx+'/order/yupaidan',{'driverid':thisbutton.attr("data-driver-id"),'orderid':$("input[name=newOrderRadios]:checked").val()},function(data){
    			if(data.success){
    				$("input[name=newOrderRadios]:checked").attr("checked",false);
    			}
    			else{
    				$.scojs_message(data.message, $.scojs_message.TYPE_ERROR);
    			}
    		});
    	}
    });
    
    //收回预派单
    $(document).on("click",".revokeYupaidan",function(){
    	$.post(ctx+'/order/revoke',{'driverid':thisbutton.attr("data-driver-id"),'orderid':$("input[name=newOrderRadios]:checked").val()},function(data){
			if(data.success){
				$("input[name=newOrderRadios]:checked").attr("checked",false);
			}
			else{
				$.scojs_message(data.message, $.scojs_message.TYPE_ERROR);
			}
		});
    });

    var thisButton;
    $(document).on("click",".revoke_yupaidan a",function(){
    	thisButton = $(this);
    	$("#dialog_revoke_id").val(thisButton.attr("data-value"));
    	$("#ok_modal_revoke").attr("disabled",false);
    	$('#dialog_revoke').modal();
    });
	$("#close_modal_revoke").click(function(){
		$('#dialog_revoke').modal("hide");
	});
	$("#ok_modal_revoke").click(function(){
		if($("#dialog_revoke_content").val().length==0){
			$.scojs_message("请填写收回原因", $.scojs_message.TYPE_ERROR);
			return;
		}
		$(this).attr("disabled",true);
		$.post($(this).attr("action"),{'id':thisButton.attr("data-value"),'content':$("#dialog_revoke_content").val()},function(data){
            if(data.success){
            	$('#dialog_revoke').modal("hide");
            }
            else{
            	$.scojs_message(data.message, $.scojs_message.TYPE_ERROR);
            }
		},'json');
	});
    
    var totalWidth=$("#totalDiv").css("width").split("px")[0];
    var rightWidth=370;
    var leftWidth=totalWidth-(rightWidth+5);
    $(".panel-left").css("width",leftWidth);
    $(".panel-right").css("width",rightWidth);
    
});

